If you are creating an HTML form, the chances are, you are going to use checkboxes and radio buttons on that form. This article explains how you can perform basic operations on these controls using JQuery.
Check or uncheck a checkbox or radio button
To check the state of the checkbox or the radio button, use the .is() method:
$("#element").is(":checked");
To check or uncheck the checkbox or the radio button, use the .prop() method:
// Check #element $( "#element" ).prop( "checked", true ); // Uncheck #element $( "#element" ).prop( "checked", false );
Retrieve the value of a checkbox or radio button
Let’s say, you have to get the value of the selected radio button, use the .val() method.
To get the value from a checked checkbox, use the following syntax:
$( "input[type=checkbox][name=bar]:checked" ).val();
To get the value from a set of radio buttons
$( "input[type=radio][name=baz]:checked" ).val();
Example
Display value of the selected radio button
Create two radio button, each for ‘male’ and ‘female’
<label><input type="radio" name="gender" value="male">Male</label> <label><input type="radio" name="gender" value="female">Female</label>
Now use the jQuery code below to show the selected value in an alert box.
$(document).ready(function(){ $("input[type='button']").click(function(){ var gender_value = $("input[name='gender']:checked").val(); if(gender_value){ alert("You are a " + gender_value); } }); });
Display values of all selected checkboxes
The code will retrieve and display all of your favorite Chinese dishes from the list. If selected, values of checked boxed will be shown, otherwise, an alert appears.
<div><input type="checkbox" value="1" class="chi"> Hot and Sour Soup</div> <div><input type="checkbox" value="2" class="chi"> Szechwan Chilli Chicken</div> <div><input type="checkbox" value="3" class="chi"> Stir Fried Tofu with Rice</div> <div><input type="checkbox" value="4" class="chi"> Chicken with Chestnuts</div> <input type="button" id="get_value" value="Confirm">
$(document).ready(function(){ $('#get_value').on('click', function(){ // Declare a checkbox array var chi_array = []; // Look for all checkboxes that have a specific class and was checked $(".chi:checked").each(function() { chi_array.push($(this).val()); }); // Join the array separated by the comma var selected; selected = chi_array.join(',') ; // Check if there are selected checkboxes if(selected.length > 0){ alert("You selecetd : " + selected); }else{ alert("Please select at least one dish."); } }); });
Comments